from flask import Flask, render_template, jsonify, request, redirect, url_for
import uuid
from datetime import datetime

app = Flask(__name__)

# 初始化默认笔记
notes = [{
    'id': 1,
    'title': 'NoteX笔记',
    'content': '在此输入你的笔记',
    'tags': ['学习'],
    'created_at': '2024-01-01'
}]

# 全局标签列表
all_tags = []

# 标签颜色映射
tag_colors = {
    '工作': 'blue',
    '会议': 'indigo',
    '学习': 'green',
    '计划': 'purple',
    '机器学习': 'yellow',
    '个人': 'pink',
    '待办': 'red',
    '重要': 'orange'
}

def get_tag_color(tag):
    if tag not in tag_colors:
        # 如果是新标签，随机分配一个颜色
        available_colors = ['blue', 'green', 'yellow', 'red', 'indigo', 'purple', 'pink', 'orange']
        tag_colors[tag] = available_colors[len(tag_colors) % len(available_colors)]
    return tag_colors[tag]

def prepare_template_data():
    """准备模板渲染所需的通用数据"""
    # 统计每个标签的使用次数
    tag_counts = {}
    for note in notes:
        for tag in note.get('tags', []):
            tag_counts[tag] = tag_counts.get(tag, 0) + 1
    
    # 获取所有唯一的标签
    all_tags = sorted(set(tag for note in notes for tag in note.get('tags', [])))
    
    # 为每个标签获取对应的颜色
    tag_color_map = {tag: get_tag_color(tag) for tag in all_tags}
    
    return {
        'all_tags': all_tags,
        'tag_counts': tag_counts,
        'tag_colors': tag_color_map
    }

@app.route('/')
def home():
    template_data = prepare_template_data()
    # 按创建时间倒序排列笔记
    sorted_notes = sorted(notes, key=lambda x: x['created_at'], reverse=True)
    return render_template('home.html', notes=sorted_notes, **template_data)

@app.route('/notes')
def all_notes():
    template_data = prepare_template_data()
    # 按创建时间倒序排列笔记
    sorted_notes = sorted(notes, key=lambda x: x['created_at'], reverse=True)
    return render_template('notes.html', notes=sorted_notes, **template_data)

@app.route('/notes/recent')
def recent_notes():
    template_data = prepare_template_data()
    # 按创建时间倒序排列笔记
    sorted_notes = sorted(notes, key=lambda x: x['created_at'], reverse=True)
    return render_template('notes.html', notes=sorted_notes, **template_data)

@app.route('/notes/new', methods=['GET', 'POST'])
def new_note():
    if request.method == 'POST':
        note = {
            'id': len(notes) + 1,
            'title': request.form.get('title'),
            'content': request.form.get('content'),
            'tags': [tag.strip() for tag in request.form.get('tags', '').split(',') if tag.strip()],
            'created_at': datetime.now().strftime('%Y-%m-%d %H:%M')
        }
        notes.append(note)
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return jsonify({'success': True, 'note': note})
        return redirect(url_for('home'))
    template_data = prepare_template_data()
    return render_template('edit_note.html', **template_data)

@app.route('/trash')
def trash():
    return render_template('trash.html')

@app.route('/register')
def register():
    return render_template('register.html')

@app.route('/ai-tech')
def ai_tech():
    return render_template('ai-tech.html')

@app.route('/notes/<int:note_id>/delete', methods=['DELETE'])
def delete_note(note_id):
    note_to_delete = next((note for note in notes if note['id'] == note_id), None)
    if note_to_delete:
        notes.remove(note_to_delete)
        return jsonify({'success': True})
    return jsonify({'success': False, 'error': 'Note not found'}), 404

@app.route('/notes/<int:note_id>/edit', methods=['GET', 'POST'])
def edit_note(note_id):
    note = next((note for note in notes if note['id'] == note_id), None)
    if not note:
        return redirect(url_for('home'))
    
    if request.method == 'POST':
        note['title'] = request.form.get('title')
        note['content'] = request.form.get('content')
        note['tags'] = [tag.strip() for tag in request.form.get('tags', '').split(',') if tag.strip()]
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return jsonify({'success': True, 'note': note})
        return redirect(url_for('home'))
    
    template_data = prepare_template_data()
    return render_template('edit_note.html', note=note, is_edit=True, **template_data)

@app.route('/save_note', methods=['POST'])
def save_note():
    try:
        title = request.form.get('title')
        content = request.form.get('content')
        tags = request.form.get('tags', '').split(',')
        tags = [tag.strip() for tag in tags if tag.strip()]  # 清理标签数据

        # 生成新的ID（使用最大ID + 1）
        new_id = max([note['id'] for note in notes], default=0) + 1

        # 保存笔记
        note = {
            'id': new_id,
            'title': title,
            'content': content,
            'tags': tags,
            'created_at': datetime.now().strftime('%Y-%m-%d %H:%M')
        }
        
        notes.append(note)

        # 返回成功响应
        return jsonify({
            'success': True, 
            'message': '笔记保存成功',
            'note': note
        })
    except Exception as e:
        print(f"保存笔记时出错: {str(e)}")  # 添加错误日志
        return jsonify({'success': False, 'message': f'保存失败: {str(e)}'}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
